package com.zl.basis.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileStoreUtil {
    private static final String TAG = "FileStoreUtil";

    public static void writeStringData(String data, String path) {
        if (null == data || data.isEmpty()) {
            return;
        }
        writeData(data.getBytes(), path);
    }

    public static String readStringData(String path) {
        return readStringData(path, null);
    }

    public static String readStringData(String path, String defaultData) {
        byte[] data = readData(path);
        if (null != data && data.length > 1) {
            return new String(data);
        }
        return defaultData;
    }

    public static void writeData(byte[] data, String path) {
        if (null == data || data.length < 1 || null == path || path.isEmpty()) {
            return;
        }
        File file = new File(path);
        if (file.isDirectory()) {
            file.delete();
        }
        if (!file.exists()) {
            file.getParentFile().mkdirs();
        }
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static byte[] readData(String path) {
        if (null == path || path.isEmpty()) {
            return null;
        }
        File file = new File(path);
        if (file.isDirectory()) {
            file.delete();
        }
        if (!file.exists()) {
            return null;
        }
        FileInputStream is = null;
        try {
            is = new FileInputStream(file);
            byte[] ret = new byte[is.available()];
            is.read(ret);
            return ret;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}
